<template>
  <van-dropdown-menu class="mb8 dropdown">
    <van-dropdown-item
      v-for="item in list"
      :ref="`dropdownItem${item.key}`"
      :key="item.key"
      :value="value[item.key]"
      :title="getTitle(item)"
      :options="getOptions(item)"
      @change="onChange(item, $event)"
    >
      <template v-if="item.type === 'cascader'">
        <van-cascader
          v-model="cascaderValue"
          :options="getCascaderOptions(item)"
          title="请选择"
          @close="close(item)"
          @finish="onFinish(item, $event)"
        >
          <template #title></template>
        </van-cascader>
      </template>
    </van-dropdown-item>
  </van-dropdown-menu>
</template>

<script>

export default {
  name: 'CDropDown',
  data() {
    return {
      cascaderValue: '',
      cascaderObj: {},
    };
  },
  props: {
    list: Array,
    value: Object,
  },
  methods: {
    onChange(item, value) {
      this.$emit('input', {
        ...this.value,
        [item.key]: value,
      });
      this.$emit('updateList');
    },
    getTitle(item) {
      if (item.type === 'cascader') {
        return this.cascaderObj.text || item.title;
      }
      if (this.value[item.key]) {
        return item.options && item.options.find(opt => opt[item.valueKey] === this.value[item.key])[item.labelKey];
      }
      return item.title;
    },
    getOptions(item) {
      if (item.type === 'cascader') return [];
      const defaultItem = [{ text: `全部${item.title}`, value: '' }];
      if (item.options.length) {
        const ret = item.options.map(opt => ({ ...opt, text: opt[item.labelKey], value: opt[item.valueKey] }));
        return defaultItem.concat(ret);
      }
      return [];
    },
    getCascaderOptions(item) {
      const mapTree = org => {
        const haveChildren = Array.isArray(org.children) && org.children.length > 0;
        return {
          text: org[item.labelKey],
          value: org[item.valueKey],
          children: haveChildren ? org.children.map(i => mapTree(i)) : null,
        };
      };
      const defaultItem = [{ text: `全部${item.title}`, value: '' }];
      let ret = [];
      if (item.options.length) {
        ret = item.options.map(opt => mapTree(opt));
      }
      return defaultItem.concat(ret);
    },
    onFinish(item, { selectedOptions }) {
      const cascaderValue = selectedOptions && selectedOptions.length ? selectedOptions.slice(selectedOptions.length - 1) : [];
      this.cascaderObj = cascaderValue.length ? cascaderValue[0] : {};
      this.$emit('input', {
        ...this.value,
        [item.key]: cascaderValue.length ? cascaderValue[0].value : '',
      });
      this.close(item);
      this.$emit('updateList');
    },
    close(item) {
      if (this.$refs[`dropdownItem${item.key}`][0].toggle) this.$refs[`dropdownItem${item.key}`][0].toggle(false);
    },
  },
};
</script>

<style lang="less" scoped>
.dropdown {
  /deep/ .van-dropdown-menu__bar {
    border-radius: 6px;
  }
}
</style>
